<script setup>
import { useUserStore } from '@/stores';
import { ref } from 'vue';
import { Plus, Upload } from '@element-plus/icons-vue'
import { userUpdataPic } from '@/api/user.js'
import { ElMessage } from 'element-plus';
const uploadRef = ref()
const userStore = useUserStore()
const imageUrl = ref(userStore.user.user_pic)

const formData = ref({
    ...userStore.user
})
// 选择文件
const onSelectPic = () => {
    uploadRef.value?.$el.querySelector('input[type="file"]').click()
}
// 文件图片url
const onChangeFile = (file) => {
    console.log(file);
    // 把获取到file对象的地址 赋值到 imageURl  在前端页面上显示
    imageUrl.value = URL.createObjectURL(file.raw)
    formData.value.user_pic = imageUrl.value
}
// 上传头像
const submitUpload = async () => {
    // 更新用户信息
    // await useUpdataInfo(formData.value)
    console.log(imageUrl.value);
    const data = await blobUrlToBase64(imageUrl.value)
    console.log(data);

    await userUpdataPic({ avatar: data })
    ElMessage.success('更换头像成功')
    // 更新仓库的信息
    userStore.getUser()


}
// blod转换成base64格式
async function blobUrlToBase64(blobUrl) {
    // 1. 获取 Blob 对象
    const response = await fetch(blobUrl);
    const blob = await response.blob();

    // 2. 转换为 Base64
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            // 移除 data:application/octet-stream;base64, 前缀（如果需要纯base64）
            // const base64String = reader.result.split(',')[1];
            resolve(reader.result); // 或者返回完整DataURL：reader.result
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
    });
}
</script>

<template>
    <PageContainer title="更换头像" class="layout">
        <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false" ref="uploadRef"
            :on-change="onChangeFile">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
        <div class="btns">
            <el-button type="primary" :icon="Plus" size="large" @click="onSelectPic">选择图片</el-button>
            <el-button type="success" :icon="Upload" size="large" @click="submitUpload">
                上传头像
            </el-button>
        </div>

    </PageContainer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
    :deep() {
        .avatar {
            width: 250px;
            height: 250px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-trandition-durantion-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 250px;
            height: 250px;
            text-align: center;

        }
    }
}

.btns {
    margin-top: 20px;
}
</style>